import React, { useEffect, useState, useRef } from 'react'
import { Space, Card, Input, Button, Switch, Modal, Form, Select, Descriptions, message } from 'antd'
import type { ColumnsType } from 'antd/es/table'
import { getUserList, createUser, modifyUser, deleteUser, modifyUserStatus, setUserRole } from '@/service/user'
import { getRolesList } from '@/service/roles'
import type { FormInstance } from 'antd/lib/form/Form'
import { useTranslation } from 'react-i18next'
import TableIndex from '@/components/table'
import Dialog from '@/components/modal'

interface DataType {
  id: number
  username: string
  email: string
  mobile: string
  role_name: string
  role_id: number
  status: number
}

type FieldType = {
  username: string
  password: string
  email?: string
  mobile?: string
}
export interface OptionType {
  id: string
  roleName: string
}
export default function Users() {
  const [condition, setCondition] = useState('')
  const [pageObj, setPageObj] = useState({
    pageNum: 1,
    pageSize: 10
  })
  const [total, setTotal] = useState(0)
  const { t } = useTranslation()
  const [dataList, setDataList] = useState<DataType[]>([])
  const [openType, setOpenType] = useState('add')
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [isRoleModalOpen, setIsRoleModalOpen] = useState(false)
  const [rowId, setRowId] = useState(0)
  const [selectedRoleId, setSelectedRoleId] = useState('')
  const [roleList, setRoleList] = useState<OptionType[]>([])
  const [userInfo, setUserInfo] = useState({
    username: '',
    role_name: ''
  })
  const formRef = useRef<FormInstance>(null)
  const columns: ColumnsType<DataType> = [
    {
      title: t('users.table.index'),
      align: 'center',
      width: 55,
      render: (text, record, index) => index + 1
    },
    {
      title: t('users.table.username'),
      dataIndex: 'username',
      key: 'username',
      align: 'center'
    },
    {
      title: t('users.table.email'),
      dataIndex: 'email',
      key: 'email',
      align: 'center'
    },
    {
      title: t('users.table.mobile'),
      dataIndex: 'mobile',
      key: 'mobile',
      align: 'center'
    },
    {
      title: t('users.table.role_name'),
      key: 'role_name',
      dataIndex: 'role_name',
      align: 'center'
    },
    {
      title: t('users.table.status'),
      key: 'status',
      align: 'center',
      render: record => <Switch checked={record.status === true} onChange={() => changeStatus(record)}></Switch>
    },
    {
      title: t('users.table.action.title'),
      key: 'action',
      align: 'center',
      render: record => (
        <Space size="middle">
          <a key="edit" onClick={() => editRow(record)}>
            {t('users.table.action.edit')}
          </a>
          <a key="del" onClick={() => delRow(record)}>
            {t('users.table.action.del')}
          </a>
          <a key="power" onClick={() => distributeRight(record)}>
            {t('users.table.action.distributeRight')}
          </a>
        </Space>
      )
    }
  ]
  useEffect(() => {
    handleSearch()
  }, [condition, pageObj])

  // 更改状态
  const changeStatus = (record: any) => {
    record.status = !record.status
    setDataList([...dataList])
    modifyUserStatus({
      id: record.id,
      state: record.status
    })
  }
  const changeCondition = (e: any) => {
    setCondition((e.target as any).value)
  }

  const handleSearch = () => {
    getUserList({
      condition: condition,
      pageNum: pageObj.pageNum,
      pageSize: pageObj.pageSize
    }).then((res: any) => {
      const { list, total } = res.data
      setDataList(list)
      setTotal(total)
    })
  }
  const handlePageChange = (pageNum: number, pageSize: number) => {
    setPageObj({
      pageNum,
      pageSize
    })
  }
  // 添加用户
  const showAddModal = () => {
    setOpenType('add')
    setIsModalOpen(true)
  }
  const handleAddModalOk = () => {
    formRef.current?.submit()
  }
  const handleAddModalCancel = () => {
    formRef.current?.resetFields()
    setIsModalOpen(false)
  }
  const onFinish = (values: any) => {
    console.log('Success:', values)
    if (openType === 'add') {
      createUser(values).then((res: any) => {
        if (res.status === 201) {
          handleAddModalCancel()
          handleSearch()
        }
      })
    } else {
      const params = {
        id: rowId,
        ...formRef.current?.getFieldsValue()
      }
      modifyUser(params).then((res: any) => {
        if (res.status === 200) {
          formRef.current?.resetFields()
          setIsModalOpen(false)
          handleSearch()
        }
      })
    }
  }
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo)
  }
  // 编辑用户信息
  const editRow = (row: DataType) => {
    setOpenType('edit')
    setIsModalOpen(true)
    setRowId(row.id)
    formRef.current?.setFieldsValue({
      username: row.username,
      email: row.email,
      mobile: row.mobile
    })
  }
  // 删除用户信息
  const delRow = (row: DataType) => {
    if (row.role_id === -1) message.warning('超级管理员不可以删除')
    deleteUser({ id: row.id }).then((res: any) => {
      if (res.status === 200) {
        handleSearch()
      }
    })
  }
  // 分配权限
  const distributeRight = (row: DataType) => {
    getRolesList().then((res: any) => {
      setRoleList(
        res.data.map((item: any) => {
          return {
            label: item.roleName,
            value: item.id
          }
        })
      )
    })
    setUserInfo({
      username: row.username,
      role_name: row.role_name
    })
    setRowId(row.id)
    setIsRoleModalOpen(true)
  }
  const handleRoleChange = (val: string) => {
    setSelectedRoleId(val)
  }
  const handleRoleModalOk = () => {
    setUserRole({
      id: rowId,
      rid: selectedRoleId
    })
    handleRoleModalCancel()
    handleSearch()
  }
  const handleRoleModalCancel = () => {
    setIsRoleModalOpen(false)
    setSelectedRoleId('')
  }

  return (
    <Card>
      <Space>
        <Input.Search
          allowClear
          style={{ width: '350px' }}
          value={condition}
          placeholder={t('users.keywords')}
          onChange={changeCondition}
          onSearch={handleSearch}
          enterButton
        />
        <Button type="primary" onClick={showAddModal}>
          {t('users.addOrEditModel.add')}
        </Button>
      </Space>
      <TableIndex
        style={{ marginTop: '20px' }}
        rowKey="id"
        columns={columns}
        dataSource={dataList}
        total={total}
        pageObj={pageObj}
        handlePageChange={handlePageChange}
      ></TableIndex>

      <Dialog
        title={openType === 'add' ? t('users.addOrEditModel.add') : t('users.addOrEditModel.edit')}
        open={isModalOpen}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <Form
          name="basic"
          ref={formRef}
          style={{ maxWidth: 600 }}
          labelCol={{ span: 4 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          layout="horizontal"
        >
          <Form.Item<FieldType>
            label={t('users.addOrEditModel.username')}
            name="username"
            rules={[{ required: true, message: t('users.addOrEditModel.required_user') }]}
          >
            <Input />
          </Form.Item>
          {openType === 'edit' ? null : (
            <Form.Item<FieldType>
              label={t('users.addOrEditModel.password')}
              name="password"
              rules={[{ required: true, message: t('users.addOrEditModel.required_pwd') }]}
            >
              <Input.Password />
            </Form.Item>
          )}
          <Form.Item<FieldType> label={t('users.addOrEditModel.email')} name="email">
            <Input />
          </Form.Item>
          <Form.Item<FieldType> label={t('users.addOrEditModel.mobile')} name="mobile">
            <Input />
          </Form.Item>
        </Form>
      </Dialog>

      <Dialog
        title={t('users.distributeRole')}
        open={isRoleModalOpen}
        onOk={handleRoleModalOk}
        onCancel={handleRoleModalCancel}
      >
        <div>
          <Descriptions column={1}>
            <Descriptions.Item label={t('users.curUser')}>{userInfo.username}</Descriptions.Item>
            <Descriptions.Item label={t('users.curRole')}>{userInfo.role_name}</Descriptions.Item>
            <Descriptions.Item label={t('users.disNewRole')}>
              <Select
                value={selectedRoleId}
                onChange={handleRoleChange}
                options={roleList}
                style={{ width: 120 }}
                size="middle"
              ></Select>
            </Descriptions.Item>
          </Descriptions>
        </div>
      </Dialog>
    </Card>
  )
}
